package com.zhiwei.controller;

import com.zhiwei.pojo.Bill;
import com.zhiwei.pojo.Order;
import com.zhiwei.pojo.Products;
import com.zhiwei.pojo.User;
import com.zhiwei.service.BillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
@CrossOrigin
@RequestMapping("/bill")
public class BillController {
    @Autowired
    private BillService billService;

    @RequestMapping("/addBill")
    public void addBill(Bill bill){
        billService.addBill(bill);
    }
    //生成发票信息的方法
    public static Bill BillGener(Order order, User dealer, Products product,User sealer) {
        //获取总金额
        BigDecimal bigDecimal = new BigDecimal(product.getUnitPrice())
                .multiply(new BigDecimal(order.getNumber()));
        Double total = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        //发票代码年份
        String year = new SimpleDateFormat("yy").format(order.getCreated());
        //发票号码
        String invoicNum = String.valueOf(System.currentTimeMillis()).substring(5);
        //密码区域
        String passWord = DigestUtils.md5DigestAsHex(String.valueOf(order.getCreated()).getBytes())
                + DigestUtils.md5DigestAsHex(invoicNum.getBytes())
                + DigestUtils.md5DigestAsHex(String.valueOf(total).getBytes());
        for (int i = 0; i < 12; i++) {
            int index = new Random().nextInt(11);
            int place = new Random().nextInt(95);
            char strIns = "./*-+=?\\|~^#".charAt(index);
            String str1 = passWord.substring(0,place);
            String str2 = passWord.substring(place);
            passWord = str1 + strIns + str2;
        }
        //校验码
        int i = new Random().nextInt(900);
        String verifyNum = String.valueOf(i + 100) + String.valueOf(System.currentTimeMillis());
        Bill bill = new Bill();
        bill.setDealer(dealer.getUsername())
                .setSalesMan(sealer.getUsername())
                .setStatus(true)
                .setBillNum("25101"+year+"240"+year)
                .setTotalPrice(total)
                .setVerifyNum(verifyNum)
                .setInvoicNum(invoicNum)
                .setRemark("诚信智为")
                .setPassWord(passWord)
                .setUpdated(order.getCreated())
                .setCreated(new Date());
        return bill;
    }
}
